import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import { downloadByData } from '/@/utils/file/download';
const { createConfirm } = useMessage();

enum Api {
  list = '/zbzh/zbzh/list',
  save = '/zbzh/zbzh/add',
  edit = '/zbzh/zbzh/edit',
  deleteOne = '/zbzh/zbzh/delete',
  deleteBatch = '/zbzh/zbzh/deleteBatch',
  importExcel = '/zbzh/zbzh/importExcel',
  exportXls = '/zbzh/zbzh/exportXls',
  exportFile = '/zbzh/zbzh/exportData',
}

/**
 * 导出api
 * @param params
 */
export const getExportUrl = Api.exportXls;

/**
 * 导入api
 */
export const getImportUrl = Api.importExcel;

/**
 * 列表接口
 * @param params
 */
export const list = (params) => defHttp.get({ url: Api.list, params });

/**
 * 删除单个
 * @param params
 * @param handleSuccess
 */
export const deleteOne = (params, handleSuccess) => {
  return defHttp.delete({ url: Api.deleteOne, params }, { joinParamsToUrl: true }).then(() => {
    handleSuccess();
  });
};

/**
 * 导出
 * @param params
 * @param handleSuccess
 */
/* export const exportFile = (params) => {
  return defHttp.get({ url: Api.exportFile, params,responseType: 'blob' }, {  joinParamsToUrl: true }).then((response) => {
    const blob = response.data;
    let fileName = '导出文件';
    console.log(response, 'blob');
  });
}; */
export const exportFile = async (params: any) => {
  try {
    const response = await defHttp.get({
      url: Api.exportFile,
      params,
      responseType: 'blob',
    });
    console.log(response,'response')
    const contentDisposition = response.headers['Content-Type'];
    let filename = '导出数据.zip';
    if (contentDisposition) {
      const match = contentDisposition.match(/filename\*?UTF-8''(.+)/);
      if (match) filename = decodeURIComponent(match[1]);
    }
    // 调用 下载
    downloadByData(response.data, filename, 'application/zip');
  } catch (error) {
    console.log(error);
    if(error.response){
      console.log(error.response)
    }
  }
};
/**
 * 批量删除
 * @param params
 * @param handleSuccess
 */
export const batchDelete = (params, handleSuccess) => {
  createConfirm({
    iconType: 'warning',
    title: '确认删除',
    content: '是否删除选中数据',
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      return defHttp.delete({ url: Api.deleteBatch, data: params }, { joinParamsToUrl: true }).then(() => {
        handleSuccess();
      });
    },
  });
};

/**
 * 保存或者更新
 * @param params
 * @param isUpdate
 */
export const saveOrUpdate = (params, isUpdate) => {
  let url = isUpdate ? Api.edit : Api.save;
  return defHttp.post({ url: url, params }, { isTransformResponse: false });
};


export default {
  methods: {
    async handleZipDownload() {
      try {
        // 1. 关键：指定responseType为blob（二进制流）
        const response = await axios({
          url: '/sys/export/zip/download', // 后端接口地址
          method: 'get',
          responseType: 'blob', // 必须设置，否则无法正确解析压缩包
          headers: {
            'X-Access-Token': localStorage.getItem('token'), // JeecgBoot 权限令牌
          },
        });

        // 2. 处理响应头，获取文件名（后端设置的Content-Disposition）
        const disposition = response.headers['content-disposition'];
        let fileName = '压缩包.zip';
        if (disposition) {
          // 解析文件名（兼容不同浏览器编码）
          fileName = decodeURIComponent(disposition.split('filename=')[1]);
        }

        // 3. 触发浏览器下载
        const blob = new Blob([response.data], { type: 'application/zip' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();

        // 4. 清理资源
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        message.success('压缩包导出成功');
      } catch (error) {
        message.error('导出失败：' + (error.message || '网络异常'));
      }
    },
  },
};